//
//  WBComposeController.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/7.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit

class WBComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.red
        setUI()
        // Do any additional setup after loading the view.
        //监听键盘弹出通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillChangeFrame(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //监听表情按钮点击通知
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonClick(noti:)), name: NSNotification.Name(rawValue: WBEmoticonButtonDidSelectedNotification), object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func back(){
        self.dismiss(animated: true, completion: nil)
    }
    /**
     监听键盘弹出通知
     - Parameters: noti-通知
     */
    @objc private func keyBoardWillChangeFrame(noti:Notification){
        //print(noti)
        //取到键盘的 frame
        let frame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        //取到键盘弹出动画时间
        let duration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        toolBar.snp_updateConstraints { (make)->Void in
            make.bottom.equalTo(self.view).offset(frame.origin.y - WBScreenH)
        }
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func emoticonButtonClick(noti:NSNotification){
        let emoticon = noti.userInfo!["emoticon"] as! WBEmoticon
        if emoticon.type == 1 {
             textView.insertText((emoticon.code! as NSString).emoji())
        }else
        {
            //图片
        }
    }
    //MARK:  -懒加载控件
    lazy var titleLabel:UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = NSTextAlignment.center
        label.font = UIFont.systemFont(ofSize: 16)
        if let name = WBUserAccountViewModel.sharedModel.account?.name{
            let title = "发微博\n\(name)"
            let attributedText = NSMutableAttributedString(string: title)
            let range = (title as NSString).range(of: name)
            attributedText.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 14),NSForegroundColorAttributeName:UIColor.darkGray], range: range)
            label.attributedText = attributedText
        }else
        {
            label.text = "发微博"
        }
        label.sizeToFit()
        return label
    }()
    lazy var textView:WBTextView = {
        let textView = WBTextView()
        textView.placeHolderText = "输入你想说的话……"
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.delegate = self
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .onDrag
        return textView
    }()
    lazy var toolBar : WBComposeToolBar = {
        let toolBar = WBComposeToolBar()
        toolBar.delegate = self
        return toolBar
    }()
    lazy var pictureView:WBComposePictureView = {
        let v = WBComposePictureView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
        //v.backgroundColor = UIColor.red
        v.backgroundColor = UIColor.white
        v.addClosure = {[weak self] in
            self?.selectPicture()
        }
        return v
    }()
    //表情键盘
    lazy var emojiKeyboard:WBEmoticonKeyboard = {
        let v = WBEmoticonKeyboard()
        v.frame.size = CGSize(width: WBScreenW, height: 216)
        return v
    }()
    //设置导航栏右边按钮
    internal lazy var rightButton: UIButton = {
        let button = UIButton()
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        // 设置不同状态的按钮背景图
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: UIControlState.disabled)
        // 设置不同状态下的按钮文字颜色
        button.setTitleColor(UIColor.gray, for: UIControlState.disabled)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitle("发送", for: UIControlState.normal)
        // 设置按钮的大小
        button.frame.size = CGSize(width: 44, height: 30)
        
        return button
        
    }()

}
extension WBComposeController:WBComposeToolBarDelegate{
    func composeTollBar(toolBar: WBComposeToolBar, buttonType: ComposeToolBarButtonType) {
        switch buttonType {
        case .picture:
            //print("pictre")
            self.selectPicture()
        case .mention:
            print("mention")
        case .trend:
            print("trend")
        case .emotion:
            print("emotion")
            //切换表情键盘
            self.changeKeyboard()
        case .add:
            print("add")
        }
    }
    
    internal func selectPicture(){
        let vc = UIImagePickerController()
        vc.sourceType = .photoLibrary
        vc.delegate = self
        self.present(vc, animated: true, completion: nil)
    }
    internal func changeKeyboard(){
        if textView.inputView == nil {
            textView.inputView = emojiKeyboard
        }else
        {
            textView.inputView = nil
        }
        if !textView.isFirstResponder{
            textView.becomeFirstResponder()
        }
        toolBar.isSystemKeyboard = textView.inputView == nil
    }
}
extension WBComposeController:UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //print(info)
        /*
         ["UIImagePickerControllerMediaType": public.image,
         "UIImagePickerControllerReferenceURL": assets-library://asset/asset.JPG?id=9F983DBA-EC35-42B8-8773-B597CF782EDD&ext=JPG, 
         "UIImagePickerControllerOriginalImage": <UIImage: 0x60000028bb30> size {3000, 2002} orientation 0 scale 1.000000]
         */
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let img = image.scaleTo(width: 400)
        pictureView.addImage(image: img)
//        let data = UIImagePNGRepresentation(img)!
//        (data as NSData).write(toFile: "/Users/bizhongyang/Desktop/aaa.png", atomically: true)
        picker.dismiss(animated: true, completion: nil)
    }
}
extension WBComposeController:UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}
extension WBComposeController{
    internal  func setUI(){
        self.view.backgroundColor = UIColor.white
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "返回", target: self, action: #selector(back))
        //
        self.navigationItem.titleView = self.titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        self.view.addSubview(textView)
        textView.snp_makeConstraints { (make)->Void in
            make.edges.equalTo(self.view)
        }
        self.view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make)->Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        textView.addSubview(pictureView)
        pictureView.snp_makeConstraints { (make)->Void in
            make.top.equalTo(textView).offset(100)
            make.left.equalTo(textView).offset(10)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
    }
    
}
